import mongodbHandle from '../handle/mongodbHandle'
import sessionHandle from '../handle/sessionHandle'
import rankHandle from '../handle/rankHandle'
import routes from './route'
var ObjectId = require('mongodb').ObjectId;
var utility = require("utility");
import app from '../app'
import * as moment from 'moment'
const jwt = require('jsonwebtoken');
import * as request from 'request'
import { PlayerModel } from 'src/core/model/playerModel'


import redisHandle from 'src/handle/redisHandle';
import playerSessionHandle from 'src/handle/playerSessionHandle';
import * as cluster from 'cluster'
import playerHandle from 'core/handle/playerHandle';
import { nbase64, nbase642 } from 'core/utils/newEnco';
import adventureHandle from 'core/handle/adventureHandle';
import { gameConfig } from 'core/config/gameConfig';
import gameHandle from 'src/handle/gameHandle';
import utils from 'core/utils/utils';
const axios = require('axios').default;

routes.setUserNotLogin('userRegister', [
    ['name', 'string'],
    ['pwd', 'string'],
    ['phone', 'string']
], async (msg) => {
    let name = msg.name
    let pwd = msg.pwd
    if (name.length > 30 || pwd.length > 30) {
        return { err: 1 }
    }
    let doc = await mongodbHandle.userDao.findOne({ name: name })
    if (doc) {
        return { err: 0, data: null, code: 1 }
    } else {
        await mongodbHandle.userDao.newAndSave(name, pwd, msg.phone || 'android')
        return { err: 0 }
    }
})

routes.setUserNotLogin('copyPlayer', [
    ['pid', 'string']
], async (msg) => {
    if (app.env == 'demo' || app.env == 'dev') {
        if (app.env == 'demo' || app.env == 'dev') {
            const axiosInstance = axios.create();
            let strdata = JSON.stringify({
                id: msg.pid
            })
            let res = await axiosInstance.post('http://darkly.qihuan.tech/admin/api/getPlayerData', strdata, { timeout: 10000 })
            return { err: 0, data: res.data.data }
        } else {
            return { err: 1 }
        }
    } else {
        return { err: 1 }
    }

})

routes.setLogin('getBakPlayer', [
    ['id', 'string'],
    ['index', 'number']
], async (msg) => {
    if ((app.env == 'demo' || app.env == 'dev')) {
        const axiosInstance = axios.create();
        let strdata = JSON.stringify({
            id: msg.id,
            index: msg.index
        })
        let res = await axiosInstance.post('http://darkly.qihuan.tech/admin/api/getBakPlayer', strdata, { timeout: 10000 })
        return { err: 0, data: res.data.data }
    } else {
        return { err: 0 }
    }
})

routes.setUserNotLogin('userLogin', [
    ['name', 'string'],
    ['pwd', 'string'],
    ['phone', 'string']
], async (msg) => {
    let name = msg.name
    let pwd = msg.pwd
    let doc = await mongodbHandle.userDao.findOne({
        name: name,
        pwd: pwd,
        // phone: msg.phone
    })
    if (doc) {
        let token = jwt.sign({
            uID: doc._id
        }, "secretkey", {
            expiresIn: '2day'
        })
        let str = await redisHandle.get(app.config.gameName + 'gameSet')
        return {
            err: 0, data: {
                gameClientConfig: str,
                token: token,
                serverID: doc.serverID
            }
        }
    } else {
        return { err: 0, data: null, code: 1 }
    }
})

routes.setNotLogin('getServerList', [], async (msg, session) => {
    let docs = await mongodbHandle.serverDao.find({})
    return { err: 0, data: docs }
})

routes.setNotLogin('getPlayers', [
    ['serverID', 'number'],
], async (msg, session, cb) => {
    let docs = await mongodbHandle.playerDao.find({
        uID: session.uID,
        currentServerID: msg.serverID
    })
    if (docs) {
        let data = docs.map(item => {
            return {
                id: item._id,
                name: item.name,
            }
        })
        return { err: 0, data: data }
    } else {
        return { err: 0, data: null }
    }
})

routes.setNotLogin('playerRegister', [
    ['serverID', 'number'],
    ['phone', 'string']
], async (msg, token, cb) => {
    let {
        serverID, phone
    } = msg
    let player = playerHandle.createPlayer(moment().valueOf())

    player = playerHandle.initPlayer(player, false, false)//================================================lcs 加了个参数 false
    let doc = await mongodbHandle.playerDao.findOne({
        uID: token.uID,
        currentServerID: serverID,
    })
    if (doc) {
        return { err: 0, data: null, code: 1 }
    } else {
        let doc = await mongodbHandle.serverDao.findOne({
            serverID: serverID,
            active: true,
        })
        if (doc) {
            if (doc.time > new Date().getTime()) {
                return { err: 0, data: null, code: 2 }
            } else {
                let res = await mongodbHandle.playerDao.newAndSave(token.uID, doc.newServerID, player, phone)
                return { err: 0, data: res }
            }
        } else {
            return { err: 0, code: 3 }
        }
    }
})

routes.setNotLogin('playerLogin', [
    ['serverID', 'number'],
    ['index', 'number']
], async (msg, token, cb) => {
    let {
        serverID,
        index
    } = msg
    let doc = await mongodbHandle.serverDao.findOne({
        serverID: serverID,
    })

    if (doc) {
        let newServerID = doc.newServerID
        let docs = await mongodbHandle.playerDao.find({
            uID: token.uID,
            currentServerID: newServerID,
        })
        if (docs) {
            let res = docs[index]
            if (res) {
                let pID = res._id.toString();
                let session = await sessionHandle.addSession(pID, token.uID, res.name)
                session.pIndex = index
                session.serverID = newServerID
                session.phone = res.phone
                sessionHandle.updateSession(session.pID, session)
                let newToken = jwt.sign({
                    uID: token.uID,
                    pID: pID,
                    serverID: newServerID,
                    sessionKey: session.sessionKey,
                    phone: res.phone,

                }, "secretkey", {
                    expiresIn: '2day'
                })

                //保存最近登录的服务器信息
                mongodbHandle.userDao.updateOne({
                    _id: ObjectId(token.uID)
                }, {
                    $set: {
                        serverID: newServerID
                    }
                })



                return { err: 0, data: { newToken, pID: pID }, code: 0 }
            } else {
                return { err: 1 }
            }
        } else {
            return { err: 0, data: null }
        }
    } else {
        return { err: 2 }
    }
})

routes.setLogin('getPlayer', [
    ['d', 'string'],
    ['o', 'number']
], async (msg, session, cb) => {
    if (msg.d == '') {
        return { err: 0 }
    }

    let res = await playerSessionHandle.savePlayerAndDelete(session.pID)

    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID)
    })

    let serverdoc = await mongodbHandle.serverDao.findOne({ serverID: session.serverID })
    if (doc) {
        let accountPlatform = doc.accountPlatform
        let nowTime = new Date().getTime()

        if (!accountPlatform) {
            let useDoc = await mongodbHandle.userDao.findOne({
                _id: ObjectId(session.uID)
            })
            let params = {
                user_id: useDoc.name,
                package_id: '305',
                timestamp: nowTime,
                sign: 'sign',
            }
            const url = `https://api.lc2game.com//cp/user/info`;
            let res = await axios.get(url, { params: params })
            if (res.data && res.data.data && res.data.data.is_taptap && res.data.data.is_taptap == 1) {
                accountPlatform = 'taptap'
            } else {
                accountPlatform = 'other'
            }
        }

        let player = doc
        let gameSetstr = await redisHandle.get(app.config.gameName + 'gameSet')

        if (player.cheat) {
            return { err: 0, data: null }
        }
        let saveAmount = doc.saveAmount || 0
        let clientLocalTime = doc.clientLocalTime || nowTime
        let overTime = doc.overTime || 0
        if ((doc.deviceID && doc.deviceID !== msg.d) || clientLocalTime > nowTime) {
            session.isClientLocal = false
            saveAmount = 0
        } else {
            session.isClientLocal = true
        }


        // if (accountPlatform !== 'taptap') {
        //     session.isClientLocal = false
        // }

        if (app.env == 'dev') {
            session.isClientLocal = true
        }

        if (doc.deviceID && doc.deviceID !== msg.d) {
            if (clientLocalTime < nowTime + 5 * 24 * 60 * 60 * 1000) {
                clientLocalTime = nowTime + 5 * 24 * 60 * 60 * 1000
            }
        }
        // if (msg.o !== 0) {
        //     if (clientLocalTime < nowTime + 20 * 60 * 1000) {
        //         clientLocalTime = nowTime + 20 * 60 * 1000
        //     }
        // }

        let arenaTimes = player.arenaTimes
        if (player.arenaTime !== moment().startOf('day').valueOf()) {
            arenaTimes = 0
        }
        if (player.playerData && app.env == "pro") {
            let routeIDs: any[] = Object.keys(player.playerData.rMapTime).map(item => { return Number(item) }).filter((item) => {
                let number = Number(item)
                if ((number >= 2 && number <= 35) || [158, 159, 160, 162, 163, 167, 168, 173, 175, 185, 213, 214, 215, 231, 232, 233].includes(number)) {
                    return true
                }
            })
            let totalTimes = 0
            routeIDs.forEach(id => {
                let times = player.playerData.rMapTime[id]
                totalTimes += times
            })
            session.cheatTimes = totalTimes
        }

        let clientplayer = {
            _id: player._id.toString(),
            id: player.id,
            chargeMoney: player.chargeMoney,
            loginTime: player.loginTime,
            saveTime: player.saveTime || 0,
            uID: player.uID,
            name: player.name,
            originServerID: player.originServerID,
            currentServerID: player.currentServerID,
            vipTime: player.vipTime,
            vip2: player.vip2 || false,
            cheat: player.cheat,
            overTime: overTime,
            clientLocalTime: clientLocalTime,
            arenaTimes: arenaTimes
        }
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(session.pID),
        }, {
            $set: {
                loginTime: new Date().getTime(),
                deviceID: msg.d,
                clientLocalTime: clientLocalTime,
                accountPlatform: accountPlatform,
            }
        })
        gameHandle.sendCumulativeRecharge(session.pID, player.chargeMoney || 0)
        sessionHandle.updateSession(session.pID, session)
        return {
            err: 0, data: {
                player: clientplayer,
                gameClientConfig: gameSetstr,
                time: new Date().getTime(),
                dtime: moment().startOf('day').valueOf(),
                isLocal: session.isClientLocal,
                saveAmount: saveAmount,
                serverTime: serverdoc ? serverdoc.time : new Date().getTime()
            }
        }
    } else {
        return { err: 0, data: null }
    }
})

routes.setLogin('getPlayerData', [

], async (msg, session, cb) => {

    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID)
    })

    if (doc) {
        let player = doc
        sessionHandle.updateSession(session.pID, session)
        let enData = nbase642.encrypt(JSON.stringify(player.playerData), 'qihuan')
        let h = utils.simpleHashWithKey(enData, 'q56789abc')
        return {
            err: 0, data: { data: enData, h: h },
        }
    } else {
        return { err: 0, data: null }
    }
})


routes.setLogin('getPlayerInfo', [], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID)
    })
    if (doc) {
        let player = doc
        player.version = app.version
        let str = await redisHandle.get(app.config.gameName + 'gameSet')
        delete player.playerData
        return { err: 0, data: { player: player, gameClientConfig: str } }
    } else {
        return { err: 0, data: null }
    }
})

routes.setLogin('getReserveData', [], async (msg, session, cb) => {
    let num = 0
    try {
        num = gameHandle.getReserveData()
        num = Number(num) || 0
    } catch (error) {
        console.log('error:', error)
    }
    return {
        err: 0,
        data: num
    }
})

routes.setLogin('savePlayer', [
    ['data', 'string'],
    ["m", 'string']
], async (msg, session, cb) => {
    if (session.isClientLocal == false) {
        return { err: 6 }
    }

    let mdhmac = utils.simpleHashWithKey(msg.data, 'q56789abc')
    if (mdhmac !== msg.m) {
        return { err: 1 }
    }

    try {
        let data = nbase642.decrypt(msg.data, 'qihuan')
        let playerData = JSON.parse(data)
        let saveTime = playerData.time
        if (playerData.id != session.pID) {
            return { err: 3 }
        }
        if (playerData.flag !== 2) {
            return { err: 0 }
        }
        let player: PlayerModel = new PlayerModel(playerData)
        let doc = await mongodbHandle.playerDao.findOne({
            _id: ObjectId(session.pID),
        })
        let nowTime = new Date().getTime()
        if (doc) {

            if (app.env == "pro" && doc.inner !== true) {
                let routeIDs = Object.keys(player.rMapTime).map(item => { return Number(item) }).filter((item) => {
                    let number = Number(item)
                    if ((number >= 2 && number <= 35) || [158, 159, 160, 162, 163, 167, 168, 173, 175, 185, 213, 214, 215, 231, 232, 233].includes(number)) {
                        return true
                    }
                })
                let totalTimes = 0
                routeIDs.forEach(id => {
                    let times = player.rMapTime[id]
                    totalTimes += times
                })
                if (session.cheatTimes !== totalTimes) {
                    return { err: 0 }
                }
            }

            if (doc.bakTime == 0 || doc.bakTime == null || (doc.bakTime + 1 * 60 * 60 * 1000) < nowTime) {
                doc.bakTime = nowTime
                let hour = 'hour' + moment().hour()
                let playerData = 'playerData' + moment().hour()
                await mongodbHandle.playerBakDao.updateOne({
                    pID: session.pID
                }, {
                    $set: {
                        time: moment().valueOf(),
                        [hour]: moment().valueOf(),
                        [playerData]: player
                    }
                }, { upsert: true })
            }

            doc.playerData = player
            let mapProgressMax = doc.mapProgressMax
            if (player && player.adventure) {
                let { total, maxTotal } = adventureHandle.getAdventureMapProgress(player)
                mapProgressMax = total
            }
            let totalPower = doc.totalPower
            if (player && player.baseInfo.power) {
                totalPower = player.baseInfo.power
            }
            let abyssProgress = doc.abyssProgress
            if (player && player.baseInfo.power) {
                let mapConfig = gameConfig.map
                let mapID = mapConfig.abyssMapID
                let floor = player.adventure.mapProgress[mapID] || 1
                abyssProgress = floor
            }

            await mongodbHandle.playerDao.updateOne({
                _id: ObjectId(session.pID),
            }, {
                $set: {
                    totalPower: totalPower,
                    playerData: player,
                    loginTime: nowTime,
                    saveTime: saveTime || nowTime,
                    mapProgressMax: mapProgressMax,
                    // phone: doc.phone || 'android',
                    arenaScore: doc.arenaScore || 100,
                    abyssProgress: abyssProgress,
                    bakTime: doc.bakTime,
                    // saveAmount: msg.sa,
                }
            })
            let reserveNum = gameHandle.getReserveData()


            return { err: 0, data: reserveNum }


        } else {
            return { err: 4 }
        }
    } catch (e) {
        return { err: 5 }
    }

})

routes.setLogin('setPlayerName', [
    ['name', 'string']
], async (msg, session, cb) => {
    let { name } = msg
    if (name && name.length > 0 && name.length <= 7) {
        // name = app.replaceSensitiveWords(name)

        // 接口 URL
        const url = 'http://common.lc2game.com/sensitive/to_word';

        // 请求参数
        const payload = {
            content: name, // 替换为你的文本内容
            login_key: '41hRU2vi8Q25mJnf'      // 替换为乐辰提供的login_key
        };

        let res = await axios.post(url, payload, {
            headers: {
                'Content-Type': 'application/json'
            }
        })

        let { data } = res;

        let { errno, msg } = data
        if (errno === 0) {
            let doc = await mongodbHandle.playerDao.findOne({
                _id: ObjectId(session.pID)
            })
            if (doc) {
                await mongodbHandle.playerDao.updateOne({
                    _id: ObjectId(session.pID),
                }, {
                    $set: {
                        name: name
                    }
                })
                return { err: 0, data: name }
            } else {
                return { err: 2 }
            }
        } else {
            return { err: 0, code: 1 }
        }

    } else {
        return { err: 1 }
    }

})

routes.setLogin('route', [
    ['rName', 'string'],
    ['fName', 'string'],
    ['s', "number"],
    ['d', "number"],
    ['t', "number"],
    ['data', "any"],
], async (msg, session, cb) => {
    // process.send({ 'message': 'route', pid: session.pID, data: msg.data, rName: msg.rName, fName: msg.fName, s: msg.s });

    let pID = session.pID
    let forkItem = app.playerSessionForksByID[pID]
    if (!forkItem) {
        let minAmount = app.playerSessionForks[0].amount
        let fork = app.playerSessionForks[0].fork
        for (let i = 0; i < app.playerSessionForks.length; i++) {
            if (app.playerSessionForks[i].amount < minAmount) {
                fork = app.playerSessionForks[i].fork
                minAmount = app.playerSessionForks[i].amount
            }
        }
        forkItem = fork
    }
    if (forkItem) {
        app.playerSessionForksByID[pID] = forkItem
        forkItem.send({ 'message': 'route', pid: session.pID, data: msg.data, rName: msg.rName, fName: msg.fName, t: msg.t, d: msg.d, s: msg.s });
    }
    return { err: 0 }
})

routes.setLogin('routeDatas', [
    ['data', 'array']
], async (msg, session, cb) => {
    let pID = session.pID
    let forkItem = app.playerSessionForksByID[pID]
    if (!forkItem) {
        let minAmount = app.playerSessionForks[0].amount
        let fork = app.playerSessionForks[0].fork
        for (let i = 0; i < app.playerSessionForks.length; i++) {
            if (app.playerSessionForks[i].amount < minAmount) {
                fork = app.playerSessionForks[i].fork
                minAmount = app.playerSessionForks[i].amount
            }
        }
        forkItem = fork
    }
    if (forkItem) {
        app.playerSessionForksByID[pID] = forkItem

        forkItem.send({ 'message': 'routeDatas', pid: session.pID, data: msg.data });
    }
    return { err: 0 }
})



routes.setLogin('getMailCount', [
], async (msg, session, cb) => {
    let count = await mongodbHandle.mailDao.count({ pID: session.pID, state: 0 })
    return { err: 0, data: count }
})

routes.setLogin('getMail', [
    ['list', 'any', false]
], async (msg, session, cb) => {
    let { list } = msg
    if (list && list.length > 0) {
        for (let i = 0; i < list.length; i++) {
            let _id = list[i]
            await mongodbHandle.mailDao.updateOne({ _id: ObjectId(_id) }, { $set: { state: 2 } })
        }
    }
    let docs = await mongodbHandle.mailDao.findByPageAndSort({ pID: session.pID, state: 0 }, { time: -1 }, 0, 40)
    return { err: 0, data: docs }
})

routes.setLogin('getMailByid', [
    ['mailid', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.mailDao.findOne({ _id: ObjectId(msg.mailid) })
    if (doc) {
        let dataStr = JSON.stringify(doc)
        let h = utils.simpleHashWithKey(dataStr, 'mail23456')
        return { err: 0, data: { data: doc, h } }
    }
    return { err: 0, code: 1 }
})

routes.setLogin('updateMailByid', [
    ['mailid', 'string']
], async (msg, session, cb) => {
    let doc = await mongodbHandle.mailDao.findOne({ _id: ObjectId(msg.mailid) })
    if (doc) {
        if (doc.state == 1) {
            await mongodbHandle.mailDao.updateOne({ _id: ObjectId(msg.mailid) }, { $set: { state: 2 } })
            return { err: 2 }
        } else if (doc.state == 0) {
            await mongodbHandle.mailDao.updateOne({ _id: ObjectId(msg.mailid) }, { $set: { state: 1 } })
            return { err: 0, data: doc }
        }
    }
    return { err: 0, code: 1 }
})

routes.setLogin('delMail', [
    ['id', 'string']
], async (msg, session, cb) => {
    await mongodbHandle.mailDao.remove({ _id: ObjectId(msg.id) })
    return { err: 0 }
})



routes.setLogin('getGift', [
    ['id', 'string'],
], async (msg, session, cb) => {
    let { id } = msg
    // if (id == "pioneertest") {
    //     let doc = await mongodbHandle.giftDao.findOne({ id: id })
    //     let data = await mongodbHandle.playerAndGiftDao.findOne({ pID: session.uID, giftID: id })
    //     if (data) {
    //         return { err: 0, code: 3 }
    //     }
    //     let uData = await mongodbHandle.userDao.findOne({ _id: ObjectId(session.uID) })
    //     if (uData.registerTime > new Date('2021-6-6').getTime()) {
    //         return { err: 0, code: 5 }
    //     }
    //     await mongodbHandle.mailDao.newAndSave(session.pID, doc.name, doc.items1, doc.items2)
    //     await mongodbHandle.playerAndGiftDao.newAndSave(session.uID, id)
    //     return { err: 0 }
    // }
    let now = new Date().getTime()
    let doc1 = await mongodbHandle.giftListDao.findOne({ id: id })
    if (doc1) {
        let doc2 = await mongodbHandle.giftDao.findOne({ id: doc1.giftTypeID })
        if (doc2) {
            if (now > doc2.endtime || now < doc2.starttime) {
                return { err: 0, code: 2 }
            }
            let data = await mongodbHandle.playerAndGiftDao.findOne({ pID: session.pID, giftID: doc1.giftTypeID })
            if (data) {
                if (doc2.multiple !== true) {
                    return { err: 0, code: 3 }
                }
                // if (data.time >= moment().valueOf()) {
                //     return { err: 0, code: 4 }
                // }
            }
            let isAddVip = false, vipTime = 0
            if (doc2.items1 && doc2.items1.length > 0) {
                for (let i = 0; i < doc2.items1.length; i++) {
                    let item = doc2.items1[i]
                    if (item[0] == 'vipTime') {
                        isAddVip = true
                        vipTime += item[1]
                        break
                    }
                }
            }
            if (!isAddVip && doc2.items2 && doc2.items2.length > 0) {
                for (let i = 0; i < doc2.items2.length; i++) {
                    let item = doc2.items2[i]
                    if (item[0] == 'vipTime') {
                        isAddVip = true
                        vipTime += item[1]
                        break
                    }
                }
            }
            if (isAddVip) {
                let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
                if (doc) {
                    let oVipTime = doc.vipTime || 0
                    if (oVipTime < now) {
                        oVipTime = now
                    }
                    await mongodbHandle.playerDao.updateOne({ _id: ObjectId(session.pID) }, {
                        $set: {
                            vipTime: oVipTime + vipTime
                        }
                    })
                }
            } else {
                await mongodbHandle.giftListDao.remove({ id: id })
                await mongodbHandle.mailDao.newAndSave(session.pID, doc2.name, doc2.items1, doc2.items2)
            }
            if (data) {
                await mongodbHandle.playerAndGiftDao.updateOne({ pID: session.pID, giftID: doc1.giftTypeID }, {
                    $set: {
                        time: moment().hour(0).minutes(0).seconds(0).milliseconds(0).valueOf(),
                        amout: (data.amount || 1) + 1
                    }
                })
            } else {
                await mongodbHandle.playerAndGiftDao.newAndSave(session.pID, doc1.giftTypeID)
            }
            return { err: 0, data: { monthVip: isAddVip } }
        }
    }
    let doc = await mongodbHandle.giftDao.findOne({ id: id })
    if (!doc || !doc.active) {
        return { err: 0, code: 1 }
    }
    if (now > doc.endtime || now < doc.starttime) {
        return { err: 0, code: 2 }
    }
    let data = await mongodbHandle.playerAndGiftDao.findOne({ pID: session.pID, giftID: id })
    if (data) {
        return { err: 0, code: 3 }
    }
    let isAddVip = false, vipTime = 0
    if (doc.items1 && doc.items1.length > 0) {
        for (let i = 0; i < doc.items1.length; i++) {
            let item = doc.items1[i]
            if (item[0] == 'vipTime') {
                isAddVip = true
                vipTime += item[1]
                break
            }
        }
    }
    if (!isAddVip && doc.items2 && doc.items2.length > 0) {
        for (let i = 0; i < doc.items2.length; i++) {
            let item = doc.items2[i]
            if (item[0] == 'vipTime') {
                isAddVip = true
                vipTime += item[1]
                break
            }
        }
    }
    if (isAddVip) {
        let player = await mongodbHandle.playerDao.findOne({ _id: ObjectId(session.pID) })
        if (doc) {
            let oVipTime = player.vipTime || 0
            if (oVipTime < now) {
                oVipTime = now
            }
            await mongodbHandle.playerDao.updateOne({ _id: ObjectId(session.pID) }, {
                $set: {
                    vipTime: oVipTime + vipTime
                }
            })
        }
    } else {
        await mongodbHandle.mailDao.newAndSave(session.pID, doc.name, doc.items1, doc.items2)
    }
    await mongodbHandle.playerAndGiftDao.newAndSave(session.pID, id)
    return { err: 0, data: { monthVip: isAddVip } }
})

routes.setLogin('playerModify', [
    ["value", "string"]
], async (msg, session, cb) => {
    let { value } = msg
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID),
    })
    if (doc) {
        let data: any = { modify: value }
        if (value == "init") {
            if (doc.modifyTime == moment().startOf('day').valueOf()) {
                if ((doc.modifyTimes || 0) >= 6) {
                    return { err: 0, code: 1 }
                } else {
                    data = { modify: value, modifyTime: moment().startOf('day').valueOf(), modifyTimes: (doc.modifyTimes || 0) + 1 }
                }
            } else {
                data = { modify: value, modifyTime: moment().startOf('day').valueOf(), modifyTimes: 0 }
            }
        }
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(session.pID),
        }, {
            $set: data
        })
    }
    return { err: 0 }
})


routes.setLogin('giftBuyTims', [], async (msg, session) => {
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID),
    })
    if (doc) {
        return {
            err: 0, data: {
                giftTime: doc.giftTime || moment().startOf('day').valueOf(),
                giftBuyTims: doc.giftBuyTims || 0
            }
        }
    }
    return {
        err: 0, data: {
            giftTime: 0,
            giftBuyTims: 0
        }
    }
})


routes.setLogin('accountCancellation', [], async (msg, session) => {
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID),
    })
    if (doc) {
        await mongodbHandle.accountCancellationDao.newAndSave(session.pID)
    }
    return {
        err: 0
    }
})


routes.setUserNotLogin('error', [
    ['pID', 'string'],
    ['error', 'string'],
    ['errorID', 'number', false]
], async (msg) => {
    let { pID, error, errorID } = msg
    mongodbHandle.errorDao.newAndSave(pID, 3, error, errorID, null)
    return {
        err: 0
    }
})

